package com.pushtalk.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
 

public class HttpUtility {
 

    private static HttpURLConnection httpConn;

    public static HttpURLConnection sendGetRequest(String requestURL)
            throws IOException {
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestProperty("Accept-Charset", "utf-8");
        httpConn.setRequestProperty("contentType", "utf-8");
        
        httpConn.setUseCaches(false);
 
        httpConn.setDoInput(true); // true if we want to read server's response
        httpConn.setDoOutput(false); // false indicates this is a GET request
 
        return httpConn;
    }
 

    public static HttpURLConnection sendPostRequest(String requestURL,
            Map<String, String> params) throws IOException {
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
 
        httpConn.setDoInput(true); // true indicates the server returns response
 
        StringBuffer requestParams = new StringBuffer();
 
        if (params != null && params.size() > 0) {
 
            httpConn.setDoOutput(true); // true indicates POST request
 
            // creates the params string, encode them using URLEncoder
            Iterator<String> paramIterator = params.keySet().iterator();
            while (paramIterator.hasNext()) {
                String key = paramIterator.next();
                String value = params.get(key);
                requestParams.append(URLEncoder.encode(key, "UTF-8"));
                requestParams.append("=").append(
                        URLEncoder.encode(value, "UTF-8"));
                requestParams.append("&");
            }
 
            // sends POST data
            OutputStreamWriter writer = new OutputStreamWriter(
                    httpConn.getOutputStream());
            writer.write(requestParams.toString());
            writer.flush();
        }
 
        return httpConn;
    }
 
    
    public static String readSingleLineRespone() throws IOException {
        //InputStream inputStream = null;
        if (httpConn != null) {
            //inputStream = httpConn.getInputStream();
            Charset charset = Charset.forName("utf-8");
            InputStreamReader  inputStream = new InputStreamReader(httpConn.getInputStream(), charset);
            BufferedReader reader = new BufferedReader(inputStream);
            
            String response = reader.readLine();
            reader.close();
     
            return response;
            
        } else {
            throw new IOException("Connection is not established.");
        }
    }
    
    public static String readSingleLineResponeGBK() throws IOException {
        //InputStream inputStream = null;
        if (httpConn != null) {
            //inputStream = httpConn.getInputStream();
            Charset charset = Charset.forName("gbk");
            InputStreamReader  inputStream = new InputStreamReader(httpConn.getInputStream(), charset);
            BufferedReader reader = new BufferedReader(inputStream);
            
            String response = reader.readLine();
            reader.close();
     
            return response;
            
        } else {
            throw new IOException("Connection is not established.");
        }
    }
 
 
    public static String[] readMultipleLinesRespone() throws IOException {
        InputStream inputStream = null;
        if (httpConn != null) {
            inputStream = httpConn.getInputStream();
            
        } else {
            throw new IOException("Connection is not established.");
        }
        Charset charset = Charset.forName("utf-8");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream,charset));
        List<String> response = new ArrayList<String>();
 
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
 
        return (String[]) response.toArray(new String[0]);
    }
     
    public static String[] readMultipleLinesResponeGBK() throws IOException {
        InputStream inputStream = null;
        if (httpConn != null) {
            inputStream = httpConn.getInputStream();
            
        } else {
            throw new IOException("Connection is not established.");
        }
        Charset charset = Charset.forName("gbk");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream,charset));
        List<String> response = new ArrayList<String>();
 
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
 
        return (String[]) response.toArray(new String[0]);
    }
     
 
    public static void disconnect() {
        if (httpConn != null) {
            httpConn.disconnect();
        }
    }
    
    public static void main(String[] args) {
        // test GET 
        //String requestURL = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.4.255.255";
        String requestURL = "http://int.dpool.sina.com.cn/iplookup/iplookup.php";
        try {
            HttpUtility.sendGetRequest(requestURL);
            String[] response = HttpUtility.readMultipleLinesResponeGBK();
            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HttpUtility.disconnect();
         
         
        System.out.println("=====================================");
         
        // test POST 
        Map<String, String> params = new HashMap<String, String>();
        requestURL = "http://cn.bing.com/search?";
        params.put("q", "java乱码");
        params.put("ip", "218.4.255.255");
         
        try {
            HttpUtility.sendPostRequest(requestURL, params);
            String[] response = HttpUtility.readMultipleLinesRespone();
            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HttpUtility.disconnect();
    }
}